<template>
	<view class="container">
		<view class="appointment-card" v-for="(item, index) in appointmentList" :key="index">
			<view class="card-header">
				<view class="title-group">
					<text class="name">参观时间:</text>
					<text class="id-card">{{ item.visitDate }} {{ item.visitTime }}</text>
				</view>
				<text class="status">
					{{ getStatusText(item.orderStatus) }}
				</text>
			</view>
			<view class="card-content">
				<text class="museum-name">胎盘文化博物馆</text>
				<view class="detail-container">
					<text class="detail-text" @click="handleDetailClick(item.id)">详情</text>
				</view>
				<!-- 	<text class="time">下单时间: {{ item.faceRecognition }}</text> -->
				<text class="time">下单时间: {{ item.orderTime }}</text>
				<view class="button-group" :class="{ 'two-btn': getStatusText(item.orderStatus) === '已预约' }">
					<view style="display: flex; justify-content: flex-end; width: 100%;"
						v-if="getStatusText(item.orderStatus) === '已预约' && item.faceRecognition!==null">
						<button class="cancel-btn" @click="cancelAppointment(item.id, index)">取消预约</button>
						<button class="verify-btn" @click="verifyByQRCode(item.id)">二维码核验</button>
					</view>
					<view style="display: flex; justify-content: flex-end; width: 100%;"
						v-if="getStatusText(item.orderStatus) === '已预约' && item.faceRecognition==null">
						<button class="cancel-btn" @click="cancelAppointment(item.id, index)">取消预约</button>
						<button class="verify-btn" @click="verifyByQRCode(item.id)">二维码核验</button>
						<button class="verify-btn" @click="startFaceVerification(item.id, item.remark)">人脸补录</button>
					</view>
					<view style="display: flex; justify-content: flex-end; width: 100%;"
						v-if="getStatusText(item.orderStatus) === '已核销'">
						<button class="continue-btn" @click="continueAppointment(item.id)">继续预约</button>
					</view>
					<view style="display: flex; justify-content: flex-end; width: 100%;"
						v-if="getStatusText(item.orderStatus) === '已取消'">
						<button class="canceled-btn" disabled>已取消</button>
					</view>
					<view style="display: flex; justify-content: flex-end; width: 100%;"
						v-if="getStatusText(item.orderStatus) === '待审核'">
						<button class="canceled-btn" disabled>等待审核</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 订单详情模态框 -->
		<view class="modal" v-if="showDetailModal">
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">订单详情</text>
					<text class="close-modal" @click="closeDetailModal">&times;</text>
				</view>
				<view class="modal-body">
					<view class="detail-table">
						<view class="table-row header-row">
							<view class="table-cell">姓名</view>
							<view class="table-cell">手机号码</view>
							<view class="table-cell">身份证号码</view>
						</view>
						<view class="table-row" v-for="(person, idx) in detailData" :key="idx">
							<view class="table-cell table-cell-text-small">{{ person.reservationName }}</view>
							<view class="table-cell table-cell-text-small">{{ person.phoneNumber }}</view>
							<view class="table-cell table-cell-text-small">{{ person.idCardNumber }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 二维码核验模态框 -->
		<view class="modal" v-if="showQRCodeModal">
			<view class="modal-content" style="padding: 30rpx;">
				<view class="modal-header">
					<text class="modal-title">二维码核验</text>
					<text class="close-modal" @click="closeQRCodeModal">&times;</text>
				</view>
				<view class="modal-body" style="text-align: center; padding: 20rpx 0;">
					<view class="qr-code-container"
						style="margin: 20rpx auto; width: 500rpx; height: 500rpx; background-color: #fff; border-radius: 10rpx; padding: 20rpx;">
						<image v-if="qrCodeData" :src="qrCodeData" mode="aspectFit"
							style="width: 100%; height: 100%;" />
						<view v-else class="loading-placeholder"
							style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;">
							<text style="color: #999;">加载中...</text>
						</view>
					</view>
					<text class="qr-code-hint"
						style="display: block; margin-top: 20rpx; font-size: 26rpx; color: #666;">请将二维码对准闸机扫描口</text>
				</view>
				<view class="modal-footer" style="text-align: center; margin-top: 20rpx;">
					<button class="close-btn" @click="closeQRCodeModal"
						style="background-color: #f5f5f5; color: #666; border-radius: 50rpx; padding: 12rpx 40rpx; font-size: 28rpx;">
						关闭
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		ordersApi
	} from '@/package/api/reservationOrders.js';
	import uploadRequest from '../../utils/uploadRequest.js'; // 引入上传工具

	const appointmentList = ref([]);
	const isLoadingDetail = ref({});
	const showDetailModal = ref(false);
	const detailData = ref([]);
	const deviceInfoList = ref([])
	const currentRemark = ref(''); // 新增：存储 remark

	// 二维码相关数据
	const showQRCodeModal = ref(false);
	const qrCodeData = ref('');
	const isLoadingQRCode = ref(false);

	// 人脸识别相关数据
	const showFaceModal = ref(false);
	const showFaceResultModal = ref(false);
	const faceImage = ref('');
	const faceFileList = ref([]); // 新增文件列表
	const currentOrderId = ref('');
	const isLoadingFace = ref(false);
	const faceResultSuccess = ref(false);
	const faceResultMessage = ref('');

	const getStatusText = (orderStatus) => {
		if (orderStatus === 0) {
			return '已预约';
		} else if (orderStatus === 1) {
			return '已核销';
		} else if (orderStatus === 2) {
			return '已取消';
		} else if (orderStatus === 3) {
			return '待审核';
		} else if (orderStatus === 4) {
			return '已失效';
		}
		return '';
	};


	onUnload(() => {
		uni.switchTab({
			url: "/pages/mine/mine"
		})
	})

	onShow(async () => {
		uni.showLoading({
			title: '加载中...'
		});
		const typeid = uni.getStorageSync("typeId");
		try {
			const response = await ordersApi.getOrdersByType(typeid);
			if (response.code === 200) {
				appointmentList.value = response.data.reservationOrdersList.map(item => ({
					...item,
					visitTime: item.visitTime || '未知时间'
				}));
				deviceInfoList.value = response.data.deviceInfoList
			}

			console.log(generateTimestampId())
		} catch (error) {
			console.error('获取订单数据失败:', error);
			uni.showToast({
				title: '获取订单数据失败，请稍后重试',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	});

	const cancelAppointment = async (orderId, index) => {
		try {
			const response = await ordersApi.edit(orderId);
			if (response.code === 200) {
				appointmentList.value[index].orderStatus = 2;
				uni.showToast({
					title: '取消预约成功',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: '取消预约失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('取消预约请求出错:', error);
			uni.showToast({
				title: '取消预约请求出错，请稍后重试',
				icon: 'none'
			});
		}
	};

	const verifyByQRCode = async (orderId) => {
		showQRCodeModal.value = true;
		isLoadingQRCode.value = true;
		try {
			const res = await ordersApi.getCode(orderId);
			if (res.code === 200 && res.data) {
				qrCodeData.value = `data:image/png;base64,${res.data}`;
			} else {
				uni.showToast({
					title: '获取二维码失败，请稍后重试',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取二维码请求出错:', error);
			uni.showToast({
				title: '获取二维码请求出错，请稍后重试',
				icon: 'none'
			});
		} finally {
			isLoadingQRCode.value = false;
		}
	};

	// 打开人脸识别时传递 remark
	const startFaceVerification = (orderId, remark) => {
		console.log(orderId)
		console.log(remark)
		// 将orderI的存在本地存储中
		uni.setStorageSync("RenLianBuLu", "人脸补录")
		uni.setStorageSync("RenLianBuLuId", orderId)

		uni.navigateTo({
			url: '/package/pages/yuYueTo/yuYueTo'
		});
	};





	const continueAppointment = (orderId) => {
		console.log('模拟继续预约操作，订单id：', orderId);
	};

	const xiangqing = async (orderId) => {
		try {
			const data = {
				orderTableId: orderId
			};
			const response = await ordersApi.getXiangQing(data);
			if (response.code === 200) {
				detailData.value = response.rows;
				showDetailModal.value = true;
			}
		} catch (error) {
			console.error('获取详情请求出错:', error);
			uni.showToast({
				title: '获取详情请求出错，请稍后重试',
				icon: 'none'
			});
		} finally {
			isLoadingDetail.value[orderId] = false;
		}
	};

	const handleDetailClick = (orderId) => {
		if (isLoadingDetail.value[orderId]) {
			return;
		}
		isLoadingDetail.value[orderId] = true;
		xiangqing(orderId);
	};

	const closeDetailModal = () => {
		showDetailModal.value = false;
		detailData.value = [];
	};

	// const closeQRCodeModal = () => {
	// 	// 在关闭二维码的时候，查询一下当前页面所有的订单重新赋值。
		
	// 	showQRCodeModal.value = false;
	// 	qrCodeData.value = '';
	// };
	
	const closeQRCodeModal = () => {
	  showQRCodeModal.value = false;
	  qrCodeData.value = '';
	
	  // 关闭模态框后，重新获取订单数据（调用 onShow 中的逻辑）
	  refreshAppointmentList();
	};
	
	// 新增：封装获取订单数据的方法（避免重复代码）
	const refreshAppointmentList = async () => {
	  uni.showLoading({ title: '加载中...' });
	  const typeid = uni.getStorageSync("typeId");
	  try {
	    const response = await ordersApi.getOrdersByType(typeid);
	    if (response.code === 200) {
	      appointmentList.value = response.data.reservationOrdersList.map(item => ({
	        ...item,
	        visitTime: item.visitTime || '未知时间'
	      }));
	      deviceInfoList.value = response.data.deviceInfoList;
	    }
	  } catch (error) {
	    console.error('刷新订单数据失败:', error);
	    uni.showToast({
	      title: '获取订单数据失败，请稍后重试',
	      icon: 'none'
	    });
	  } finally {
	    uni.hideLoading();
	  }
	};

	const closeFaceModal = () => {
		showFaceModal.value = false;
		faceImage.value = '';
		faceFileList.value = [];
		isLoadingFace.value = false;
	};

	const closeFaceResultModal = () => {
		showFaceResultModal.value = false;
		faceResultSuccess.value = false;
		faceResultMessage.value = '';
		if (showFaceModal.value) {
			showFaceModal.value = false;
		}
	};


	/**
	 * 生成基于当前时间戳的8位数字字符串
	 * @returns {string} 8位数字字符串
	 */
	function generateTimestampId() {
		// 获取当前时间戳（毫秒）
		const timestamp = Date.now();

		// 将时间戳转换为字符串
		const timestampStr = timestamp.toString();

		// 提取时间戳的最后8位数字
		let shortId = timestampStr.slice(-8);

		// 如果时间戳不足8位，前面补0
		if (shortId.length < 8) {
			shortId = shortId.padStart(8, '0');
		}

		return "RL" + shortId;
	}

	// 示例使用
	// const id = generateTimestampId();
	// console.log(id); // 输出类似 "12345678" 的8位数字字符串    
</script>

<style>
	.container {
		padding: 40rpx;
		background-color: #f8f9fa;
	}

	.appointment-card {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
		border-bottom: 2rpx solid #e0e0e0;
	}

	.title-group {
		display: flex;
		flex-direction: row;
		gap: 20rpx;
		align-items: center;
	}

	.name {
		font-size: 30rpx;
		font-weight: 500;
		color: #333333;
	}

	.id-card {
		font-size: 26rpx;
		color: #666666;
	}

	.status {
		color: #666666;
		font-size: 26rpx;
	}

	.card-content {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		min-height: 180rpx;
	}

	.museum-name {
		font-size: 30rpx;
		margin-bottom: 12rpx;
		color: #333333;
	}

	.time {
		color: #999999;
		font-size: 26rpx;
		margin-bottom: 20rpx;
	}

	.button-group {
		margin-top: auto;
		display: flex;
		flex-direction: column;
		gap: 12rpx;
		width: 100%;
	}

	.button-group.two-btn {
		flex-direction: row;
		gap: 16rpx;
	}

	.cancel-btn,
	.verify-btn,
	.canceled-btn,
	.continue-btn {
		padding: 10rpx 18rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 28rpx;
		font-size: 24rpx;
		min-width: 120rpx;
		margin: 8px;
		border-radius: 50rpx;
		width: 82px;
	}

	.verify-btn {
		color: #409eff;
		background-color: #ecf5ff;
		border-color: #d9ecff;
	}

	.canceled-btn {
		color: #cccccc;
		background-color: #f5f5f5;
		border-color: #e9e9e9;
	}

	.continue-btn {
		color: #409eff;
		background-color: #f0f5ff;
		border-color: #e6ecff;
	}

	.detail-container {
		width: 100%;
		display: flex;
		justify-content: flex-end;
		margin: 8rpx 0;
	}

	.detail-text {
		font-size: 24rpx;
		color: #409eff;
		text-decoration: underline;
	}

	.card-content {
		min-height: auto;
	}

	.museum-name {
		margin-bottom: 4rpx;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.modal-content {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 24rpx;
		width: 80%;
		max-width: 600rpx;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
		border-bottom: 2rpx solid #e0e0e0;
	}

	.modal-title {
		font-size: 30rpx;
		font-weight: 500;
		color: #333333;
	}

	.close-modal {
		font-size: 36rpx;
		color: #666666;
		cursor: pointer;
	}

	.detail-table {
		width: 100%;
		border-collapse: collapse;
		margin-top: 10px;
	}

	.table-row {
		display: flex;
		border-bottom: 1px solid #ddd;
	}

	.table-cell {
		padding: 12rpx 15rpx;
		border-right: 1px solid #ddd;
		text-align: left;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		flex: 1;
	}

	.table-cell:last-child {
		border-right: none;
	}

	.header-row {
		background-color: #f2f2f2;
		font-weight: bold;
	}

	.table-row:nth-child(even) {
		background-color: #f9f9f9;
	}

	.table-row:hover {
		background-color: #f1f1f1;
	}

	.table-cell-text-small {
		font-size: 25rpx;
	}

	.face-container {
		padding: 20rpx;
	}

	.face-placeholder {
		border: 2rpx dashed #ddd;
		border-radius: 10rpx;
		padding: 60rpx 0;
		margin-bottom: 20rpx;
		cursor: pointer;
	}

	.loading-indicator {
		margin-top: 20rpx;
	}

	.result-icon {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin: 0 auto;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.success {
		background-color: #e6f7ff;
		color: #1890ff;
	}

	.fail {
		background-color: #fff2f0;
		color: #ff4d4f;
	}

	.icon-text {
		font-size: 50rpx;
		font-weight: bold;
	}
</style>